package com.imooc.miaosha.validator;

import com.imooc.miaosha.util.ValidatorUtil;
import org.thymeleaf.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 *  手机号码的校验器
 */
public class IsMobileValidator  implements ConstraintValidator<IsMobile,String> {
   private boolean required = false;
    /**
     * 初始化方法
     * @param isMobile
     */
    @Override
    public void initialize(IsMobile isMobile) {
        required = isMobile.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(required){
            return ValidatorUtil.isMobile(value);
        }else{
            if(StringUtils.isEmpty(value)){
                return true;
            }
            else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}
